<template>
  <el-container v-loading="" style="padding: 15px">
    <el-header height="180px">
      <el-divider>项目进度</el-divider>
      <el-row type="flex" :gutter="0" align="middle" justify="end" style="margin: 1% 0">
        <el-col :lg="5" :xl="4" :push="1">
          <el-button v-if="hasRole(['audit', 'admin'])" type="danger" size="small" :disabled="reportStatus.num > 5" @click="toBackReportLeaf">退回</el-button>
          <el-button type="info" size="small" @click="auditRecordDialogOpenHandler">审核记录</el-button>
          <el-button v-if="hasRole(['audit', 'admin'])" type="success" size="small" @click="pass">通过</el-button>
        </el-col>
      </el-row>
      <el-steps :active="reportStatus.num" align-center>
        <el-step title="创建报告" icon="el-icon-circle-plus" />
        <el-step title="撰写报告" icon="el-icon-edit" />
        <el-step title="一审" icon="el-icon-s-check" />
        <el-step title="二审" icon="el-icon-s-check" />
        <el-step title="三审" icon="el-icon-s-check" />
        <!--        <el-step v-if="reportCommonObj.projectId !== '6'" title="终审" icon="el-icon-s-check" />-->
        <el-step title="用印申请" icon="el-icon-s-grid" />
        <el-step title="归档" icon="el-icon-s-claim" />
      </el-steps>
      <el-row type="flex" :gutter="0" align="middle" style="margin: 1% 0">
        <el-col :span="6">
          <el-button v-if="hasRole(['audit', 'admin'])" type="danger" size="small" @click="termination">终止</el-button>
          <el-button v-if="hasRole(['finance', 'administrative', 'admin'])" type="warning" size="small" :disabled="reportStatus.num != 5" @click="toStampAudit">用印</el-button>
          <el-button v-if="hasRole(['valuer', 'audit', 'admin'])" type="success" size="small" :disabled="reportStatus.num != 1" @click="pushAudit">提交</el-button>
          <el-button v-if="hasRole(['admin'])" type="success" size="small" @click="amend">修改</el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-form ref="reportDetailForm" :model="reportCommonObj" :rules="initReportFormRule" size="small" label-width="100px" :disabled="(reportStatus.num > 2 || reportStatus.num=== -1) && amendvale">
        <report-info :report-common-obj="reportCommonObj" :is-audit="isAudit" style="margin-left: -100px" />
        <client-info :report-common-obj="reportCommonObj" :is-audit="isAudit" style="margin-left: -100px" />
      </el-form>
      <el-form size="small" label-width="100px">
        <RiskAssessment :report-common-obj="reportCommonObj" :is-audit="isAudit" style="margin-left: -100px" />
      </el-form>
      <el-form size="small" label-width="100px">
        <administrative-info v-if="hasRole(['administrative', 'admin'])" :report-status="reportStatus.num" :report-common-obj="reportCommonObj" :is-audit="isAudit" :audit-leaf="reportStatus" style="margin-left: -100px" />
      </el-form>
      <el-form size="small" label-width="100px">
        <administrative-stamp-info v-if="hasRole(['finance', 'administrative', 'admin'])" :report-common-obj="reportCommonObj" :is-audit="isAudit" :audit-leaf="reportStatus" style="margin-left: -100px" />
      </el-form>
      <finance-info v-if="hasRole(['finance', 'admin'])" :report-common-obj="reportCommonObj" :is-audit="isAudit" />
      <file-info />
      <el-row type="flex" align="middle" style="margin-top: 1%">
        <el-col :span="9" style="margin: 0 auto">
          <el-button type="primary" :disabled="isAudit" @click="saveReport('reportDetailForm')">保存</el-button>
          <el-button type="info" :disabled="isAudit" @click="resetReport">重置</el-button>
          <el-button v-if="hasRole(['valuer', 'audit', 'admin'])" type="success" size="small" :disabled="reportStatus.num != 1" style="margin-left: 70px" @click="pushAudit('reportDetailForm')">提交</el-button>
          <el-button v-if="hasRole(['audit', 'admin'])" type="success" size="small" @click="pass">通过</el-button>
        </el-col>
      </el-row>
    </el-main>
    <el-dialog
      title="提示"
      :visible.sync="auditRecordDialogVisible"
      destroy-on-close
      width="80%"
      :before-close="auditRecordDialogBeforeClose"
    >
      <el-row type="flex">
        <el-col>
          <el-button type="primary" size="small" :loading="downloadRecordButtonLoading" @click="downloadRecord">下载</el-button>
        </el-col>
      </el-row>
      <el-table :data="auditRecordList">
        <el-table-column label="审核时节点名" prop="auditInLeafName" />
        <el-table-column label="审核人员账户名" prop="auditUserName" />
        <el-table-column label="审核人员昵称" prop="auditNickName" />
        <el-table-column label="审核时状态" prop="auditStatusIn">
          <template v-slot="scope">
            <el-tag v-if="scope.row.auditStatusIn === 1" type="success">未审核</el-tag>
            <el-tag v-if="scope.row.auditStatusIn === 2" type="info">审核中</el-tag>
            <el-tag v-if="scope.row.auditStatusIn === 3" type="warning">审核通过</el-tag>
            <el-tag v-if="scope.row.auditStatusIn === 4" type="danger">审核未通过</el-tag>
            <el-tag v-if="scope.row.auditStatusLast === 5" type="danger">审核终止</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核后状态" prop="auditStatusLast">
          <template v-slot="scope">
            <el-tag v-if="scope.row.auditStatusLast === 1" type="success">未审核</el-tag>
            <el-tag v-if="scope.row.auditStatusLast === 2" type="info">审核中</el-tag>
            <el-tag v-if="scope.row.auditStatusLast === 3" type="warning">审核通过</el-tag>
            <el-tag v-if="scope.row.auditStatusLast === 4" type="danger">审核未通过</el-tag>
            <el-tag v-if="scope.row.auditStatusLast === 5" type="danger">审核终止</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核后节点名" prop="auditLastLeafName" />
        <el-table-column label="审核时间" prop="auditTime" :formatter="tableTimeFormat" />
      </el-table>
      <el-pagination
        :current-page="auditRecordCurrentPage"
        :page-sizes="[10, 20, 40, 80]"
        :page-size="auditRecordSizePage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="auditRecordTotal"
        @size-change="auditRecordSizePageHandler"
        @current-change="auditRecordCurrentPageHandler"
      />
    </el-dialog>
  </el-container>
</template>

<script>
import ReportInfo from '@/views/report-server/report/details-report/component/report-info'
import ClientInfo from '@/views/report-server/report/details-report/component/client-info'
import AdministrativeInfo from '@/views/report-server/report/details-report/component/administrative-info'
import FinanceInfo from '@/views/report-server/report/details-report/component/finance-info'
import FileInfo from '@/views/report-server/report/details-report/component/file-info'
import AdministrativeStampInfo from '@/views/report-server/report/details-report/component/administrative-stamp-info'
import RiskAssessment from '@/views/report-server/report/details-report/component/risk-assessment'

import { isvalidPhone } from '@/utils/validate'
import { getReportInfo, getReportStatusById, updateReport } from '@/api/report'
import { mapGetters } from 'vuex'
import {
  auditRecordList,
  backReportLeaf,
  updateReportLeaf,
  auditPassReport,
  submitAudit,
  stampAudit,
  downloadReportRecord,
  auditTerminationReport
} from '@/api/flow'
import { parseTime } from '@/utils'

export default {
  name: 'Index',
  components: { FileInfo, FinanceInfo, AdministrativeInfo, ClientInfo, ReportInfo, AdministrativeStampInfo, RiskAssessment },
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const valuerCheck = (rule, value, callback) => {
      if (this.reportCommonObj.reportObjectiveId === '5' || this.reportCommonObj.reportObjectiveId === '6') {
        callback()
      } else if (this.reportCommonObj.reportObjectiveId !== '5' || this.reportCommonObj.reportObjectiveId !== '6') {
        if (this.reportCommonObj.signUserId1 !== null && this.reportCommonObj.signUserId1 !== '') {
          callback()
        } else {
          callback(new Error('请填写签字估价师'))
        }
      } else {
        callback()
      }
    }

    const valuerSubLevel = (rule, value, callback) => {
      if (this.reportCommonObj.bankId === '1') {
        if (this.reportCommonObj.channelSubBranchId !== null && this.reportCommonObj.channelSubBranchId !== '') {
          callback()
        } else {
          callback(new Error('请填写子级名称'))
        }
      } else {
        callback()
      }
    }
    return {
      initReportFormRule: {
        channelId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        chargeGist: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        reportProvideTime: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        startAndEndTime: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        bankId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        signUserId1: [
          { required: true, trigger: 'change', validator: valuerCheck }
        ],
        signUserId2: [
          { required: true, trigger: 'change', validator: valuerCheck }
        ],
        channelSubBranchId: [
          { required: true, trigger: 'change', validator: valuerSubLevel }
        ],
        reportName: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        clientUserName: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        clientFullName: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        clientUserPhone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        customerUserName: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        customerUserPhone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        reportId: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        beLocated: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        prefectureLevelCities: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        area: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        department: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        amountOfAgreement: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        reportBuildingArea: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        reportPropertyOwner: [
          { required: true, trigger: 'blur', message: '该选项为必填项' }
        ],
        projectId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        reportTypeId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        reportEvaluateTime: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        reportUseId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        reportObjectiveId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        valueUserId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        reportEvaluateMethodId1: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ],
        businessUserId: [
          { required: true, trigger: 'change', message: '该选项为必填项' }
        ]
      },
      reportCommonObj: {},

      flowFontColor: 'white',
      flowContainerColor: '#0a76a4',

      isAudit: false,
      amendvale: true,

      reportStatus: 0,

      auditRecordDialogVisible: false,
      infoLoading: false,

      downloadRecordButtonLoading: false,

      auditRecordList: [],

      auditRecordCurrentPage: 1,
      auditRecordSizePage: 10,
      auditRecordTotal: 0

    }
  },

  created() {
    this.init()
  },

  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapGetters([
      'id',
      'roles'
    ])
  },

  methods: {

    auditRecordSizePageHandler(val) {
      this.auditRecordSizePage = val
      this.auditRecordDialogOpenHandler()
    },

    auditRecordCurrentPageHandler(val) {
      this.auditRecordCurrentPage = val
      this.auditRecordDialogOpenHandler()
    },

    init() {
      const id = this.$route.query.id
      this.getReportInfo(id)
      this.getReportStatus(id)
    },

    saveReport() {
      this.$confirm('确认进行更改吗？', '修改报告信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.save().then(() => {
          this.audit(1).finally(() => {
            this.init()
          })
        })
      })
    },

    getReportStatus(id) {
      getReportStatusById(id).then(res => {
        this.reportStatus = res.data.reportStatus
      })
    },

    async save() {
      const reportCommonObj = this.reportCommonObj
      if (reportCommonObj.billCharge !== null) {
        if (Number(reportCommonObj.amountOfAgreement) !== Number(reportCommonObj.billCharge)) {
          this.$message({
            message: '协议金额与实际到账开票金额存在不同',
            type: 'warning'
          })
        }
      }
      console.log(reportCommonObj)
      await updateReport(reportCommonObj).then(res => {
        this.$message.success(res.message)
      })
    },

    getReportInfo(id) {
      getReportInfo(id).then(res => {
        this.reportCommonObj = res.data.reportUpdateForm
      })
    },

    resetReport() {
      this.$confirm('确认进行重置操作吗?', '重置信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        const id = this.$route.query.id
        this.getReportInfo(id)
        // 重置成功提示框
        this.$message({
          message: '重置成功',
          type: 'success'
        })
      })
    },

    hasRole(role) {
      const roles = this.roles
      const filter = roles.filter(v => role.includes(v))
      return filter.length !== 0
    },

    pushAudit() {
      console.log(this.reportCommonObj)
      this.$refs.reportDetailForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交后将自动保存当前报告信息，并且自动通过报告一审，确定提交当前的报告信息吗？', '提交审核', {
            confirmButtonText: '提交',
            cancelButtonText: '取消'
          }).then(() => {
            this.save().then(() => {
              const id = this.$route.query.id
              submitAudit(id, this.id).finally(res => {
                this.$message.success(res.message)
              })
            }).finally(() => {
              this.$router.go(0)
            })
          })
        } else {
          this.$message.error('请检查表单是否填写完整')
        }
      })
    },

    toStampAudit() {
      this.$confirm('请确保信息已保存，确定提交当前的报告信息吗？', '用印通过', {
        confirmButtonText: '提交',
        cancelButtonText: '取消'
      }).then(() => {
        this.save().then(() => {
          const id = this.$route.query.id
          stampAudit(id, this.id).finally(res => {
            this.$message.success(res.message)
            this.init()
          })
        }).finally(() => {
          this.$router.go(0)
        })
      })
    },

    pass() {
      this.$confirm('确认之后将修改报告的审核状态，并且自动生成审核记录，继续吗？', '通过审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(res => {
        const id = this.id
        const id1 = this.$route.query.id
        auditPassReport(id1, id).then(res => {
          this.$message.success(res.message)
          this.$router.push({ path: '/audit/pool' })
        })
      })
    },
    termination() {
      this.$confirm('当前操作不可逆,将终止此报告,请在需要作废的位置填上  是', '终止审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(res => {
        const id = this.id
        const id1 = this.$route.query.id
        auditTerminationReport(id1, id).then(res => {
          this.$message.success(res.message)
          this.$router.go(0)
        })
      })
    },
    amend() {
      this.amendvale = !this.amendvale
    },

    packReportLeafObj() {
      const reportId = this.$route.query.id
      const reportStatus = this.reportStatus
      const auditUserId = this.id
      return {
        reportId: reportId,
        leafId: reportStatus.id,
        auditUserId: auditUserId
      }
    },

    async audit(statusNum) {
      const data = this.packReportLeafObj()
      await updateReportLeaf(data, statusNum)
    },

    auditDialogHandler() {
      this.$confirm('此操作将改变当前状态，并且自动生成审核记录，确认继续吗？', '确认通过', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.audit(3).finally(() => {
          this.init()
        })
      })
    },

    toBackReportLeaf() {
      const data = this.packReportLeafObj()
      this.$confirm('此操作将改变当前状态，并且自动生成审核记录，确认继续吗？', '状态退回', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        backReportLeaf(data).then(res => {
          this.$message.success(res.message)
          this.init()
        })
      })
    },

    auditRecordDialogBeforeClose() {
      this.auditRecordDialogVisible = false
      this.auditRecordList = []
    },

    tableTimeFormat(row, column, cellValue, index) {
      return parseTime(cellValue, '')
    },

    auditRecordDialogOpenHandler() {
      const reportId = this.$route.query.id
      auditRecordList(reportId, this.auditRecordCurrentPage, this.auditRecordSizePage).then(res => {
        const data = res.data
        this.auditRecordList = data.list
        this.auditRecordTotal = data.total
        this.auditRecordDialogVisible = true
      })
    },

    downloadRecord() {
      this.downloadRecordButtonLoading = true
      const id = this.$route.query.id
      downloadReportRecord(id).then(res => {
        const url = window.URL.createObjectURL(new Blob([res], { type: res.type }))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', id + '.xlsx')
        document.body.appendChild(link)
        link.click()
        this.downloadButtonLoading = false
      }).finally(() => {
        this.downloadRecordButtonLoading = false
      })
    }
  }
}
</script>

<style scoped>
.step_container{
  border: 1px solid black;
  border-radius: 100%;
  width: 100%;
  height: 75px;
}

.step_container_title_font{
  font-weight: bolder;
  font-size: 12px;
  margin-top: 38%;
  margin-left: 3%;
}

.step{
  margin: 0 auto;
  width: 45%;
  text-align: center;
  float: left
}
</style>
